package com.fantabest.console.client.widget;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Layout;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.fantabest.common.client.AppEvents;
import com.fantabest.common.client.FantaBestConstants;
import com.fantabest.common.client.RegistryKeys;
import com.fantabest.common.client.SeasonServiceAsync;
import com.fantabest.common.client.StoreManager;
import com.fantabest.common.entity.Season;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class SeasonManagementPanel extends LayoutContainer {

	private SeasonServiceAsync service = Registry.get(RegistryKeys.SEASON_SERVICE);
	private FantaBestConstants constants = Registry.get(RegistryKeys.CONSTANTS);
	
	private EditorGrid<BeanModel> seasonGrid;
	private CheckBoxSelectionModel<BeanModel> sm;  
  
	private Button saveGrid;
	
	public SeasonManagementPanel() {
		super();
		initUI();
	}

	public SeasonManagementPanel(Layout layout) {
		super(layout);
		initUI();
	}

	private void initUI()	{
		this.setLayout(new BorderLayout());
		
		LayoutContainer leftContainer = new LayoutContainer(new FitLayout());
		BorderLayoutData leftContainerData = new BorderLayoutData(LayoutRegion.WEST);
		leftContainer.setStyleAttribute("paddingRight", "10px");
		leftContainerData.setSize(500);
		
		ContentPanel gridPanel = new ContentPanel(new FitLayout());		
		gridPanel.setBodyBorder(false);  
		gridPanel.setTopComponent(createSeasonGridToolBar());
//		gridPanel.setIcon(Examples.ICONS.table());  
		gridPanel.setHeading(constants.seasonsList());  
		seasonGrid = createSeasonGrid();
		gridPanel.add(seasonGrid);
		saveGrid = new Button(constants.save(), IconHelper.createStyle("save16"));
		saveGrid.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				persistChanges();
			}
		});
		gridPanel.addButton(saveGrid);
		leftContainer.add(gridPanel);
		
		this.add(leftContainer, leftContainerData);
		
		LayoutContainer rightContainer = new LayoutContainer();
		BorderLayoutData rightContainerData = new BorderLayoutData(LayoutRegion.CENTER);
		
		this.add(rightContainer,rightContainerData);
	}
	
	/**
	 * Creo la grid
	 * @return
	 */
	private EditorGrid<BeanModel> createSeasonGrid() {
		sm = new CheckBoxSelectionModel<BeanModel>();
		final EditorGrid<BeanModel> grid = new EditorGrid<BeanModel>(StoreManager.getInstance().getSeasonStore(), createColumnModel());
		grid.addPlugin(sm);
		grid.setAutoExpandColumn("description");
	    grid.setSelectionModel(sm);
		grid.setLoadMask(true);
		grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {
			public void handleEvent(GridEvent<BeanModel> be) {
				grid.getStore().getLoader().load();
			}
		});
		return grid;
	}

	private ColumnModel createColumnModel()	{
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		
		columns.add(sm.getColumn());
		
		ColumnConfig columnConfig = new ColumnConfig("id", constants.id(), 20); 
		columns.add(columnConfig);
		
		columnConfig = new ColumnConfig("title", constants.title(), 100);
		TextField<String> titleText = new TextField<String>();
		titleText.setAllowBlank(false);
		columnConfig.setEditor(new CellEditor(titleText));
		columns.add(columnConfig);
		
		columnConfig = new ColumnConfig("description", constants.description(), 120);
		TextField<String> descriptionText = new TextField<String>();
		descriptionText.setAllowBlank(false);
		columnConfig.setEditor(new CellEditor(descriptionText));
		columns.add(columnConfig);
		
		columnConfig = new ColumnConfig("start", constants.start(), 70);
		DateField startDate = new DateField();
		startDate.setAllowBlank(false);
		startDate.setEditable(false);
		columnConfig.setEditor(new CellEditor(startDate));
		columnConfig.setDateTimeFormat(DateTimeFormat.getShortDateFormat());
		columns.add(columnConfig);
		
		columnConfig = new ColumnConfig("end", constants.end(), 70);
		DateField endDate = new DateField();
		endDate.setAllowBlank(false);
		endDate.setEditable(false);
		columnConfig.setEditor(new CellEditor(endDate));
		columnConfig.setDateTimeFormat(DateTimeFormat.getShortDateFormat());
		columns.add(columnConfig);
		return new ColumnModel(columns);
	}
	
	private ToolBar createSeasonGridToolBar()	{
		ToolBar bar = new ToolBar();
		bar.setAlignment(HorizontalAlignment.RIGHT);
		Button btn = new Button(constants.createNew(), IconHelper.createStyle("add16"));  
		btn.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				Season season = new Season();
				season.setTitle(constants.newSeason());
				seasonGrid.getStore().insert(BeanModelLookup.get().getFactory(Season.class).createModel(season),0);
				seasonGrid.startEditing(0, 1);
			}
		});
		bar.add(btn);  
		btn = new Button(constants.delete(), IconHelper.createStyle("remove16"));  
		btn.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				Season season = new Season();
				season.setTitle(constants.newSeason());
				List<BeanModel> selectedItems = seasonGrid.getSelectionModel().getSelectedItems();
				for (Iterator<BeanModel> iterator = selectedItems.iterator(); iterator
						.hasNext();) {
					BeanModel beanModel = iterator.next();
					seasonGrid.getStore().remove(beanModel);
				}
			}
		});
		bar.add(btn);  
		return bar;
	}
	
	private void persistChanges()	{
		List<BeanModel> modifiedRecords = seasonGrid.getStore().getRange(0, seasonGrid.getStore().getCount()-1);
		List<Season> seasonsList = new ArrayList<Season>();
		for (Iterator<BeanModel> iterator = modifiedRecords.iterator(); iterator.hasNext();) {
			BeanModel beanModel = iterator.next();
			seasonsList.add((Season)beanModel.getBean());
		}
		
		service.saveAll(seasonsList, new AsyncCallback<Void>() {

			public void onFailure(Throwable caught) {
				Dispatcher.get().dispatch(AppEvents.Error, caught);
			}

			public void onSuccess(Void result) {
				seasonGrid.getStore().getLoader().load();
				Registry.unregister(RegistryKeys.SEASON_STORE);
			}
		});
	}
}
